use crate::utils::constant::get_local_json_path;
use serde::{Deserialize, Serialize};
use serde_json::from_str;
use std::fs::File;
use std::io;
use std::io::{Read, Write};

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct ProjectList {
    pub project_list: Vec<ProjectInfo>,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct ProjectInfo {
    pub id: String,
    pub name: String,
    pub project_type: String,
    pub lang: String,
    pub os_type: String,
    pub arch: String,
    pub path: String,
    pub is_compiled: bool,
}

/// 设置本地缓存数据
pub fn set_local_value(value: ProjectList) -> io::Result<()> {
    let json = serde_json::to_string_pretty(&value)?;
    let local_file = get_local_json_path();
    let mut file = File::options()
        .write(true)
        .create(true)
        .open(local_file.as_path())?;
    // 格式化写文件
    file.write_all(json.as_bytes())?;
    file.flush()?;
    Ok(())
}

pub fn get_local_value() -> io::Result<ProjectList> {
    let local_file = get_local_json_path();
    if !local_file.exists() {
        return Ok(ProjectList {
            project_list: vec![],
        });
    }
    let mut file = File::options()
        .read(true)
        .open(local_file.as_path())
        .expect("open local file failed");
    let mut content = String::new();
    file.read_to_string(&mut content)
        .expect("read local file failed");
    let value: ProjectList = from_str(&content)?;
    Ok(value)
}
